package com.wanmait.bootdemo.interceptor;

import com.wanmait.bootdemo.annotation.IgnoreToken;
import com.wanmait.bootdemo.pojo.Admin;
import com.wanmait.bootdemo.service.AdminService;
import com.wanmait.bootdemo.util.CookieUtils;
import com.wanmait.bootdemo.util.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

@Component
public class JWTAuthcInterceptor implements HandlerInterceptor {
    @Resource
    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断handler是否映射到方法 如果不是不用验证
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        //判断方法上有没有@IgnoreToken注解
        Method method = handlerMethod.getMethod();
        if(method.isAnnotationPresent(IgnoreToken.class)){
            IgnoreToken ignoreToken = method.getAnnotation(IgnoreToken.class);
            if(ignoreToken.required()){
                return true;
            }
        }
        //其他全部进行token验证
        //从cookie中获得token
        String token = CookieUtils.getCookieValue(request,"token");
        if(token==null){
            //从请求头中获得token
            token = request.getHeader("token");
        }
        if(token==null){
            throw new Exception("没有登录");
        }
        HttpSession session = request.getSession();
        if(token.equals(session.getAttribute("token"))){
            return true;
        }
        //从token中获得管理员的id
        Integer id = Integer.parseInt(JWTUtils.getAudience(token));
        //查询管理员
        Admin admin = adminService.findById(id);
        if(admin==null){
            throw new Exception("该用户不存在，验证失败");
        }
        //验证token 传递密钥
        JWTUtils.verifyToken(token,admin.getPassword());
        //验证通过
        request.getSession().setAttribute("token",token);
        //方便控制器中使用
        request.setAttribute("admin",admin);
        return true;
    }
}
